package com.crazymaker.cloud.alertmanager.demo.controller;

import com.crazymaker.springcloud.common.util.JsonUtil;
import com.crazymaker.springcloud.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/hook")
@Slf4j
public class AlertManagerDemoController {


    public static final Map<String, Object> ALERT_FAIL = new HashMap<>();
    public static final Map<String, Object> ALERT_SUCCESS = new HashMap<>();

    static {
        ALERT_FAIL.put("msg", "报警失败");
        ALERT_FAIL.put("code", 0);
        ALERT_SUCCESS.put("msg", "报警成功");
        ALERT_SUCCESS.put("code", 1);
    }


    @RequestMapping(value = "/demo", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String pstn(@RequestBody String json) {
        log.debug("alert notify  params: {}", json);

        if (StringUtils.isBlank(json)) {
            return JsonUtil.pojoToJson(ALERT_FAIL);//告警发送失败
        }
        Map<String, Object> jo = JsonUtil.jsonToMap(json);

        //获取 标签
        Map<String, Object> annotations = (Map<String, Object>) jo.get("commonAnnotations");

        if (annotations == null) {
            return JsonUtil.pojoToJson(ALERT_FAIL);//告警发送失败
        }


        Object status = jo.get("status");
        Object subject = annotations.get("summary");
        Object content = annotations.get("description");
        log.error("status: {}", status);
        log.error("summary: {}", subject);
        log.error("content: {}", content);

        //开发发送短信
        List<String> users = getRelatedPerson();

        try {
            boolean success = sendMsg(subject, content, users);
            if (success) {
                return JsonUtil.pojoToJson(ALERT_SUCCESS);//告警发送成功
            }
        } catch (Exception e) {
            log.error("=alert sms notify error. json={}", json, e);
        }
        return JsonUtil.pojoToJson(ALERT_FAIL);//告警发送失败

    }
    //todo  发送短信

    private boolean sendMsg(Object subject, Object content, List<String> users) {
        return true;
    }


    //todo  从配置中心，加载短信号码
    private List<String> getRelatedPerson() {
        return Collections.emptyList();
    }


}
